We will be using the Asia network (http://www.bnlearn.com/bnrepository/#asia) and do some inference queries.


In [1]:
# Fetching the network
import wget
import gzip
f = wget.download('http://www.bnlearn.com/bnrepository/asia/asia.bif.gz')
with gzip.open('asia.bif.gz', mode='rb') as f:
    file_content=f.read()
with open('asia.bif', mode='wb') as f:
    f.write(file_content)

In [2]:
from pgmpy.readwrite import BIFReader
reader = BIFReader('asia.bif')
!rm asia.bif
asia_model = reader.get_model()

In [3]:
asia_model.nodes()


Out[3]:
NodeView(('asia', 'tub', 'smoke', 'lung', 'bronc', 'either', 'xray', 'dysp'))

In [4]:
asia_model.edges()


Out[4]:
OutEdgeView([('asia', 'tub'), ('tub', 'either'), ('smoke', 'lung'), ('smoke', 'bronc'), ('lung', 'either'), ('bronc', 'dysp'), ('either', 'xray'), ('either', 'dysp')])

In [5]:
asia_model.get_cpds()


Out[5]:
[<TabularCPD representing P(asia:2) at 0x7f0887ffa978>,
 <TabularCPD representing P(bronc:2 | smoke:2) at 0x7f0887ffa8d0>,
 <TabularCPD representing P(dysp:2 | bronc:2, either:2) at 0x7f0887fa0550>,
 <TabularCPD representing P(either:2 | lung:2, tub:2) at 0x7f0887fa0ac8>,
 <TabularCPD representing P(lung:2 | smoke:2) at 0x7f0887fa0d68>,
 <TabularCPD representing P(smoke:2) at 0x7f0887fa0e48>,
 <TabularCPD representing P(tub:2 | asia:2) at 0x7f0887fa0b70>,
 <TabularCPD representing P(xray:2 | either:2) at 0x7f0887fa0f28>]

In [6]:
# Doing exact inference using Variable Elimination
from pgmpy.inference import VariableElimination
asia_infer = VariableElimination(asia_model)

# Computing the probability of bronc given smoke.
q = asia_infer.query(variables=['bronc'], evidence={'smoke': 'no'})
print(q)


Finding Elimination Order: : 100%|██████████| 6/6 [00:00<00:00, 4080.06it/s]
Eliminating: xray: 100%|██████████| 6/6 [00:00<00:00, 546.62it/s]
+------------+--------------+
| bronc      |   phi(bronc) |
+============+==============+
| bronc(yes) |       0.3000 |
+------------+--------------+
| bronc(no)  |       0.7000 |
+------------+--------------+


In [7]:
q = asia_infer.query(variables=['bronc'], evidence={'smoke': 'yes'})
print(q)


Finding Elimination Order: : 100%|██████████| 6/6 [00:00<00:00, 3569.62it/s]
Eliminating: xray: 100%|██████████| 6/6 [00:00<00:00, 683.22it/s]
+------------+--------------+
| bronc      |   phi(bronc) |
+============+==============+
| bronc(yes) |       0.6000 |
+------------+--------------+
| bronc(no)  |       0.4000 |
+------------+--------------+


In [ ]: